package com.work.demo.service;

import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;

@Service
public class SSLService {

	/**
	 * 客户端证书路径
	 */
	private final static String CLIENT_CERT_FILE = "C:\\Users\\admin\\Desktop\\client.p12";
	/**
	 * 客户端证书密码
	 */
	private final static String CLIENT_PWD = "mldnjava";
	/**
	 * 信任库文件路径
	 */
	private final static String TRUST_STRORE_FILE = "C:\\Users\\admin\\Desktop\\test.truststore";
	/**
	 * 信任库密码
	 */
	private final static String TRUST_STORE_PWD = "mldnjava";

	private static String readResponseBody(InputStream inputStream) throws IOException {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
			StringBuilder sb = new StringBuilder();
			String buff = null;
			while ((buff = br.readLine()) != null) {
				sb.append(buff).append("\n");
			}
			return sb.toString();
		} finally {
			inputStream.close();
		}
	}

	private static void httpsCall() throws Exception {
		// 初始化密钥库
		KeyManagerFactory keyManagerFactory = KeyManagerFactory
						.getInstance("SunX509");
		KeyStore keyStore = getKeyStore(CLIENT_CERT_FILE, CLIENT_PWD, "PKCS12");
		keyManagerFactory.init(keyStore, CLIENT_PWD.toCharArray());
		// 初始化信任库
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
						.getInstance("SunX509");
		KeyStore trustKeyStore = getKeyStore(TRUST_STRORE_FILE, TRUST_STORE_PWD, "JKS");
		trustManagerFactory.init(trustKeyStore);
		// 初始化SSL上下文
		SSLContext ctx = SSLContext.getInstance("SSL");
		ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory
						.getTrustManagers(), null);
		SSLSocketFactory sf = ctx.getSocketFactory();
		HttpsURLConnection.setDefaultSSLSocketFactory(sf);
		String url = "https://cas.com";
		URL urlObj = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
		con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 " +
						"(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
		con.setRequestProperty("Accept-Language", "zh-CN;en-US,en;q=0.5");
		con.setRequestMethod("GET");
		String res = readResponseBody(con.getInputStream());
		System.out.println(res);
	}

	/**
	 * 获得KeyStore
	 */
	private static KeyStore getKeyStore(String keyStorePath, String password, String type)
					throws Exception {
		FileInputStream is = new FileInputStream(keyStorePath);
		KeyStore ks = KeyStore.getInstance(type);
		ks.load(is, password.toCharArray());
		is.close();
		return ks;
	}

	public static void main(String[] args) throws Exception {
		httpsCall();
	}
}